package com.leetcode;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * 20. 有效的括号
 *
 * @author fy
 * @date 2022/4/11 21:55
 */
public class Solution20 {

    private final static Map<Character, Character> CHS = new HashMap<Character, Character>(3) {
        {
            put('(', ')');
            put('{', '}');
            put('[', ']');
        }
    };

    public boolean isValid(String s) {
        if (s == null || s.length() <= 1) {
            return false;
        }
        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (CHS.containsKey(ch)) {
                stack.push(ch);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char left = stack.pop();
                if (CHS.get(left) != ch) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

}
